<template>
    <div class="admin-profile">
      <h1>管理员个人信息管理</h1>
      
      <el-tabs v-model="activeTab" type="card">
        <el-tab-pane label="个人信息" name="info">
          <el-card class="profile-card">
            <template #header>
              <div class="card-header">
                <span>基本信息</span>
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="editInfoMode = true"
                  v-if="!editInfoMode"
                >
                  编辑信息
                </el-button>
              </div>
            </template>
            
            <el-form 
              :model="userInfo" 
              label-width="100px" 
              v-if="editInfoMode"
            >
              <el-form-item label="用户名">
                <el-input v-model="userInfo.userName" disabled></el-input>
              </el-form-item>
              <el-form-item label="手机号">
                <el-input v-model="userInfo.telephone"></el-input>
              </el-form-item>
              <el-form-item label="用户角色">
                <el-input v-model="userInfo.userRole" disabled></el-input>
              </el-form-item>
              <el-form-item label="登录次数">
                <el-input v-model="userInfo.loginCount" disabled></el-input>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveUserInfo">保存</el-button>
                <el-button @click="cancelEditInfo">取消</el-button>
              </el-form-item>
            </el-form>
            
            <div class="info-display" v-else>
              <div class="info-item">
                <span class="info-label">用户名：</span>
                <span class="info-value">{{ userInfo.userName }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">手机号：</span>
                <span class="info-value">{{ userInfo.telephone || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">用户角色：</span>
                <span class="info-value">{{ userInfo.userRole }}</span>
              </div>
            </div>
          </el-card>
        </el-tab-pane>
        
        <el-tab-pane label="修改密码" name="password">
          <el-card class="password-card">
            <template #header>
              <div class="card-header">
                <span>修改密码</span>
              </div>
            </template>
            
            <el-form 
              :model="passwordForm" 
              :rules="passwordRules" 
              ref="passwordFormRef"
              label-width="120px"
            >
              <el-form-item label="原密码" prop="oldPassword">
                <el-input 
                  v-model="passwordForm.oldPassword" 
                  type="password" 
                  show-password
                  placeholder="请输入当前密码"
                ></el-input>
              </el-form-item>
              
              <el-form-item label="新密码" prop="newPassword">
                <el-input 
                  v-model="passwordForm.newPassword" 
                  type="password" 
                  show-password
                  placeholder="请输入新密码"
                ></el-input>
              </el-form-item>
              
              <el-form-item label="确认新密码" prop="confirmPassword">
                <el-input 
                  v-model="passwordForm.confirmPassword" 
                  type="password" 
                  show-password
                  placeholder="请再次输入新密码"
                ></el-input>
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="submitPasswordChange">提交修改</el-button>
                <el-button @click="resetPasswordForm">重置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </div>
  </template>
  
  <script>
  import { ref, reactive, onMounted } from 'vue'
  import axios from 'axios'
  import { ElMessage } from 'element-plus'
  import { useUserStore } from '@/stores/user' // 导入Pinia store
  
  export default {
    name: 'AdminProfile',
    setup() {
      const userStore = useUserStore() // 使用Pinia store
      
      // 当前激活的标签页
      const activeTab = ref('info')
      
      // 用户信息相关
      const userInfo = reactive({
        userId: '',
        userName: '',
        telephone: '',
        userRole: '',
        registerTime: '',
        lastLoginTime: '',
        loginCount: 0
      })
      
      const editInfoMode = ref(false)
      const originalInfo = ref({})
      
      // 密码修改相关
      const passwordFormRef = ref(null)
      const passwordForm = reactive({
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      })
      
      // 密码验证规则
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else if (value.length < 6) {
          callback(new Error('密码长度不能少于6位'))
        } else {
          if (passwordForm.confirmPassword !== '') {
            passwordFormRef.value.validateField('confirmPassword')
          }
          callback()
        }
      }
      
      const validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      
      const passwordRules = reactive({
        oldPassword: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, validator: validatePass, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, validator: validatePass2, trigger: 'blur' }
        ]
      })
      
      // 获取当前用户信息
      const fetchUserInfo = async () => {
        try {
          // 从Pinia store中获取用户信息
          if (userStore.userInfo) {
            Object.assign(userInfo, userStore.userInfo)
            originalInfo.value = { ...userStore.userInfo }
            return
          }
          
          // 如果store中没有，从API获取
          const userId = localStorage.getItem('userId')
          if (!userId) {
            ElMessage.error('无法获取用户信息，请重新登录')
            return
          }
          
          const response = await axios.get(`http://localhost:8080/hospital5_war/user/findById/${userId}`)
          Object.assign(userInfo, response.data)
          originalInfo.value = { ...response.data }
          // 将用户信息存入Pinia store
          userStore.setUserInfo(response.data)
        } catch (error) {
          ElMessage.error('获取用户信息失败: ' + error.message)
        }
      }
      
      // 保存用户信息
      const saveUserInfo = async () => {
        try {
          const response = await axios.post('http://localhost:8080/hospital5_war/user/updateUserInfo', userInfo)
          
          if (response.status === 200) {
            ElMessage.success('用户信息更新成功')
            editInfoMode.value = false
            // 更新Pinia store中的用户信息
            userStore.setUserInfo(userInfo)
          } else {
            ElMessage.error('用户信息更新失败')
          }
        } catch (error) {
          ElMessage.error('用户信息更新失败: ' + error.message)
        }
      }
      
      // 取消编辑
      const cancelEditInfo = () => {
        Object.assign(userInfo, originalInfo.value)
        editInfoMode.value = false
      }
      
      // 提交密码修改
      const submitPasswordChange = () => {
        passwordFormRef.value.validate(async (valid) => {
          if (valid) {
            try {
              const params = {
                userId: userInfo.userId,
                oldPassword: passwordForm.oldPassword,
                newPassword: passwordForm.newPassword
              }
              
              const response = await axios.post('http://localhost:8080/hospital5_war/user/updatePassword', params)
              
              if (response.data.success) {
                ElMessage.success('密码修改成功')
                resetPasswordForm()
              } else {
                ElMessage.error(response.data.message || '密码修改失败')
              }
            } catch (error) {
              ElMessage.error('密码修改失败: ' + error.message)
            }
          } else {
            ElMessage.error('请正确填写表单')
            return false
          }
        })
      }
      
      // 重置密码表单
      const resetPasswordForm = () => {
        passwordFormRef.value.resetFields()
      }
      
      // 组件挂载时获取用户信息
      onMounted(() => {
        fetchUserInfo()
      })
      
      return {
        activeTab,
        userInfo,
        editInfoMode,
        passwordForm,
        passwordFormRef,
        passwordRules,
        saveUserInfo,
        cancelEditInfo,
        submitPasswordChange,
        resetPasswordForm
      }
    }
  }
  </script>
  
  <style scoped>
  .admin-profile {
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
  }
  
  .profile-card, .password-card {
    margin-top: 20px;
  }
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .info-display {
    padding: 0 20px;
  }
  
  .info-item {
    margin-bottom: 15px;
    font-size: 14px;
  }
  
  .info-label {
    display: inline-block;
    width: 100px;
    color: #606266;
    font-weight: bold;
  }
  
  .info-value {
    color: #303133;
  }
  
  .el-form {
    margin-top: 20px;
  }
  </style>